<template>
  <el-dialog :title="formData.id?'编辑员工':'新增员工'" :visible="showDialog" width="40%" @close="closeFn">
    <el-form ref="form" label-position="top" :rules="rules" :model="formData">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" />
      </el-form-item>
    </el-form>

    <el-row type="flex" justify="center">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="confirmFn">确 定</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { editorEmployee, addEmployee } from '@/api/employees'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        username: '',
        email: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
          // { min: 2, max: 6, message: '用户名长度为2-6个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' }
          // { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
          // { min: 6, max: 12, message: '密码长度为6至12位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {

    // -----确认按钮-----
    async confirmFn() {
      await this.$refs.form.validate()

      if (this.formData.id) {
        await editorEmployee(this.formData)
        // this.$message.success('编辑成功')
      } else {
        await addEmployee(this.formData)
        // this.$message.success('新增成功')
      }
      this.closeFn()
      this.$emit('updateEvent')
    },

    // -----关闭弹窗函数-----
    closeFn() {
      this.formData = {
        username: '',
        email: '',
        password: ''
      }
      this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
    }
  }
}
</script>

<style>

</style>
